<?php
declare(strict_types=1);
/**
 * Created by PhpStorm
 * User: Administrator
 * Date: 2023/8/10
 * Time: 09:58:53
 */

namespace Service\WebSocketService;

use Service\Code\Normal;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;

class GoodsBrandService extends \Service\BaseService
{

    /**
     * 品牌导入
     * @param $server
     * @param int $fd
     * @param array $body
     * @param int $manager_id
     * @param int $cid
     * @return array
     */
    public function import($server,int $fd,array $body,int $manager_id,int $cid){
        if(!isset($body['file']) || !$body['file']){
            return Normal::returnCode(Normal::FAIL,'缺少导入文件');
        }

        $rename = time();
        $url = $body['file'];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
        $rawdata = curl_exec ($ch);
        curl_close($ch);
        $path = __DIR__ . '/../../uploads/';
        if(!file_exists($path)){
            mkdir($path,0777,true);
        }
        $ext = pathinfo($url)['extension'];
        $fp = fopen($path.$rename.'.'.$ext,'w');
        fwrite($fp, $rawdata);
        fclose($fp);
        $file = realpath($path.$rename.'.'.$ext);
        try{
            $objRead = IOFactory::createReader('Xlsx');
            if (!$objRead->canRead($file)) {
                $objRead = IOFactory::createReader('Xls');
                if (!$objRead->canRead($file)) {
                    throw new \Exception('只支持导入Excel文件！');
                }
            }

            /* 如果不需要获取特殊操作，则只读内容，可以大幅度提升读取Excel效率 */
            empty($options) && $objRead->setReadDataOnly(true);

            /* 建立excel对象 */
            $obj = $objRead->load($file);

            /* 获取指定的sheet表 */
            $currSheet = $obj->getSheet(0);

            if (isset($options['mergeCells'])) {
                /* 读取合并行列 */
                $options['mergeCells'] = $currSheet->getMergeCells();
            }

            /* 取得最大的列号 */
            $columnH = $currSheet->getHighestColumn();
            /* 兼容原逻辑，循环时使用的是小于等于 */
            $columnCnt = Coordinate::columnIndexFromString($columnH);

            /* 获取总行数 */
            $rowCnt = $currSheet->getHighestRow();
            $data = [];



            /* 读取内容 */
            for ($_row = 1; $_row <= $rowCnt; $_row++) {
                $isNull = true;
                for ($_column = 1; $_column <= $columnCnt; $_column++) {
                    $cellName = Coordinate::stringFromColumnIndex($_column);
                    $cellId = $cellName . $_row;
                    $cell = $currSheet->getCell($cellId);
                    $data[$_row][$cellName] = trim($currSheet->getCell($cellId)->getFormattedValue());
                    if (!empty($data[$_row][$cellName])) {
                        $isNull = false;
                    }
                }
                if ($isNull) {
                    unset($data[$_row]);
                }
            }
            if (is_dir($file)) {
                rmdir($file);
            }
            return Normal::returnCode(Normal::SUC,'读取成功',$data);
        }catch (\Exception $e){
            return Normal::returnCode(Normal::FAIL,'导入失败：'.$e->getMessage());
        }

    }
}